package website.haicheng.cloudauth.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import website.haicheng.api.entity.SysLogs;
import website.haicheng.api.service.LogService;
import website.haicheng.cloudauth.dto.LoginDto;
import website.haicheng.cloudauth.entity.UserInfo;
import website.haicheng.cloudauth.mapper.UserInfoMapper;
import website.haicheng.cloudauth.service.IUserInfoService;
import website.haicheng.cloudauth.util.IpUtils;
import website.haicheng.core.constant.RedisPrefix;
import website.haicheng.core.exceptions.auth.AuthException;
import website.haicheng.core.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 582895699@qq.com
 * @since 2021-02-10
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    public static final String SEPARATE = ":";

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private LogService logService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 最多允许登录错误的次数
     */
    public static final Integer ALLOWED_LOGIN_NUMBER = 3;


    @Override
    public UserInfo login(LoginDto dto, HttpServletRequest request) {
        Integer loginCount = (Integer) redisTemplate.opsForValue().get(RedisPrefix.AUTH_MODULE_PREFIX + SEPARATE + dto.getAccount());
        if (Objects.nonNull(loginCount) && loginCount >= ALLOWED_LOGIN_NUMBER) {
            redisTemplate.expire(RedisPrefix.REPEAT_LOGIN + SEPARATE + dto.getAccount(), 2L, TimeUnit.HOURS);
            throw new AuthException("登录次数过多，账号已被冻结");
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getAccount, dto.getAccount());
        UserInfo currentUser = userInfoMapper.selectOne(queryWrapper);

        if (Objects.isNull(currentUser)) {
            redisTemplate.opsForValue().increment(RedisPrefix.AUTH_MODULE_PREFIX + SEPARATE + dto.getAccount());
            throw new AuthException("用户名或密码错误");
        }

        Boolean deleted = currentUser.getIsDelete();
        Assert.stat(deleted, "账号已注销");

        Boolean enabled = currentUser.getEnable();
        Assert.stat(enabled, "账户已被冻结");

        String pwd = SecureUtil.sha1(currentUser.getSalt() + dto.getPassword());
        if (!pwd.equals(currentUser.getPassword())) {
            redisTemplate.opsForValue().increment(RedisPrefix.AUTH_MODULE_PREFIX + SEPARATE + dto.getAccount());
            throw new AuthException("用户名或密码错误");
        }

        SysLogs sysLogs = new SysLogs();
        sysLogs.setAccount(dto.getAccount());
        sysLogs.setIp(IpUtils.getIpFromRequest(request));
        sysLogs.setDesc("登录成功");
        sysLogs.setTime(LocalDateTime.now());
        logService.saveAccessLog(sysLogs);
        return currentUser;
    }
}
